import classNames from 'classnames';
import { ChangeEvent, forwardRef, InputHTMLAttributes, useState } from 'react';
import style from './Input.module.scss';

export type Props = InputHTMLAttributes<HTMLInputElement> & {
  label?: string;
  hint?: string;
  error?: any;
  asterisked?: boolean;
  regex?: RegExp;
};

const Input = forwardRef<HTMLInputElement, Props>(
  (
    {
      label,
      hint,
      error,
      asterisked = false,
      className,
      disabled,
      autoComplete = 'off',
      onChange,
      regex,
      ...props
    },
    ref,
  ) => {
    const [value, setValue] = useState<string>();
    const onInput = (v: ChangeEvent<HTMLInputElement>) => {
      if (regex !== undefined && regex.test(v.target.value) === false) return;
      setValue(v.target.value);
      onChange && onChange(v);
    };

    return (
      <div>
        {label && (
          <div className={classNames(style.label, { [style.labelDisabled]: disabled })}>
            {label}
            {asterisked && <span className={style.asterisk}>*</span>}
          </div>
        )}
        <input
          className={classNames(style.input, className, {
            [style.error]: !!error,
            [style.disabled]: disabled,
          })}
          disabled={disabled}
          autoComplete={autoComplete}
          ref={ref}
          value={value}
          onChange={onInput}
          {...props}
        />
        {typeof error === 'string' && <div className={style.errorMessage}>{error}</div>}
        {hint && <div className={style.hint}>{hint}</div>}
      </div>
    );
  },
);

Input.displayName = 'Input';

export default Input;
